import React, { useEffect, useState } from "react";
import { createForm } from "rc-form";
import { List, InputItem, Toast } from "antd-mobile";
import Button from "../../../components/button";
import AgreeItem from "../../../components/agreeItem";
import "./index.scss";

const pattern = {
	// email: /^([A-Za-z0-9_\-.])+@([A-Za-z0-9_\-.])+\.([A-Za-z]{2,4})$/,
	idCard: /(^\d{15,18}$)|(^\d{17}(\d|X|x)$)/,
	userName: /^[\u4e00-\u9fa5]{1,30}$/
	// bankCard: /^[1-9]\d{9,29}$/,
	// phone: /^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/,
	// code: /^\d{6}$/,
	// password: /^\d{6}$/
};

const Form = props => {
	const [checked, setChecked] = useState(false);
	const { values, submit, form, disabled, isHiddenBotton } = props;
	const { getFieldProps, getFieldError, validateFields, setFieldsValue } = form;

	useEffect(() => {
		if (values) {
			setFieldsValue(values);
		}
	}, [values]);
	const checkCredit = e => {
		e.preventDefault();
		props.history.push({
			pathname: "/personalCreditAuthorization",
			params: {}
		});
	};

	const onErrorClick = name => {
		const message = getFieldError(name).join("、");
		Toast.fail(message);
	};
	const fieldPropsMap = {
		userName: {
			rules: [
				{
					required: true,
					message: "请输入姓名"
				},
				{
					message: "姓名格式不正确",
					pattern: pattern.userName
				}
			]
		},
		idNo: {
			rules: [
				{
					required: true,
					message: "请输入身份证号"
				},
				{
					message: "请输入正确的身份证号",
					pattern: pattern.idCard
				}
			]
		}
	};
	const submitHandle = () => {
		if (!checked && props.currentCode !== "804") {
			return Toast.info("请先勾选协议", 2);
		}
		if (disabled) {
			return submit();
		}
		validateFields((err, values) => {
			if (!err || disabled) {
				if (submit) {
					submit(values);
				}
			}
		});
	};
	const checkedHandle = e => {
		setChecked(e.target.checked);
	};
	return (
		<div className="form-component-wrapper">
			<List>
				<InputItem
					{...getFieldProps("userName", fieldPropsMap.userName)}
					error={getFieldError("userName")}
					onErrorClick={() => onErrorClick("userName")}
					disabled={disabled}
					type="text"
				>
					姓名
				</InputItem>
				<InputItem
					{...getFieldProps("idNo", fieldPropsMap.idNo)}
					error={getFieldError("idNo")}
					onErrorClick={() => onErrorClick("idNo")}
					disabled={disabled}
					type="text"
				>
					身份证号
				</InputItem>
			</List>

			{props.currentCode !== "804" && (
				<AgreeItem
					className="form-component-wrapper-checkbox"
					onChange={checkedHandle}
					onClick={checkCredit}
				>
					《个人征信授权书》
				</AgreeItem>
			)}
			<p className="form-component-wrapper-message">
				我司正规持牌机构，全程信息加密处理，保障您的隐私安全
			</p>
			<Button
				isHiddenBotton={isHiddenBotton}
				onClick={submitHandle}
				style={{ marginTop: "0.78rem" }}
			>
				确认绑定
			</Button>
		</div>
	);
};
export default createForm()(Form);
